<script setup lang="ts">
import useStore from '@/store/index'
import {usePagination} from "@/hooks/pagination.ts";
import {computed, ComputedRef, reactive, ref} from "vue";
import {ConfirmAqiDataDto} from "@/ts/entityTypes.ts";
import {codeToText, provinceAndCityData} from "element-china-area-data";
import ConfirmAqiPreview from "@/components/supervision/ConfirmAqiPreview.vue";
import {confirmAqiDataApi} from "@/api/confirmAqiDataApi.ts";
import {ElMessage} from "element-plus";

const store = useStore()
store.homeTitle = '确认AQI数据列表'

let tableData = reactive<Array<ConfirmAqiDataDto>>([])
let selectForm = reactive({
  province: '',
  city: '',
  dateRange: ''
})
let previewData = ref<ConfirmAqiDataDto>()
const showPreview = ref(false)

const emit = defineEmits<{
  (e: 'getAddress', data: {
    code: string[] //区域码
    name: string[] //汉字
    isComplete: boolean  //是否选择完整，方便校验
  }): void
}>()


let address = reactive<{
  province: string
  city: string
}>({
  province: '',
  city: ''
})

interface AreaList {
  value: string
  label: string
}

const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!address.province) { return [] }
  let temp = provinceAndCityData.find((item: any) => {
    return item.value == address.province
  })
  return temp?.children ? temp.children : []
})


const handleProvinceSelect = () => {
  address.city = ''
  emit('getAddress', {
    code: [address.province], //区域码
    name: [codeToText[address.province]], //汉字
    isComplete: false
  })
}

const aqiOptions = [
  { value: 0, label: '全部' , color: '#33c2f1'},
  { value: 1, label: '优（一）' , color: '#00ff00'},
  { value: 2, label: '良（二）' , color: '#ffff00'},
  { value: 3, label: '轻度污染（三）' , color: '#ff7f00'},
  { value: 4, label: '中度污染（四）' , color: '#ff0000'},
  { value: 5, label: '重度污染（五）' , color: '#8b00ff'},
  { value: 6, label: '严重污染（六）' , color: '#8b0000'}
]
const shortcuts = [
  {
    text: '这个月',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().getFullYear(), new Date().getMonth())
      return [start, end]
    }
  },
  {
    text: '今年',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().getFullYear(), 0)
      return [start, end]
    },
  },
  {
    text: '过去半年',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 6)
      return [start, end]
    },
  },
]

const aqiToObj = (level: number) => {
  let option = aqiOptions.find((item)=>{
    return item.value == level
  })
  return option ? [option] : []
}

const handlePreview = (index: number, row: ConfirmAqiDataDto) => {
  previewData.value = row
  showPreview.value = true
}

const handleClosePreview = (val: boolean) => {
  showPreview.value = val
}

const clearForm = () => {
  address.province = ''
  address.city = ''
  selectForm.dateRange = ''
}

const initData = async () =>{
  tableData.splice(0, tableData.length)
  let res = await confirmAqiDataApi({
    page: page.value,
    pageSize: pageSize.value,
    province: address.province,
    city: address.city,
    startDate: selectForm.dateRange[0],
    endDate: selectForm.dateRange[1]
  }).catch(err => {
    ElMessage.error(err)
  })
  if (res?.data.code == 200){
    tableData.push(...res.data.data.data)
    counts.value = res.data.data.total
  } else {
    ElMessage.error(res?.data.msg)
  }
}

const {page,
  pageSize,
  counts,
  tableLoading,
  handleCurrentChange,
  handleSizeChange} = usePagination(initData)
</script>

<template>
<div class="main-box">
  <el-form style="width: 100%; margin-top: 1rem" :model="selectForm" v-if="!showPreview">
    <el-row :gutter="50" style="width: 100%">
      <el-col :offset="1" :span="5">
        <el-form-item label="省区域" prop="province">
          <el-select clearable v-model="address.province" placeholder="请选择省" @change="handleProvinceSelect">
            <el-option v-for="item in provinceAndCityData" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="市区域" prop="city">
          <el-select clearable v-model="address.city" placeholder="请选择市" :disabled="!address.province || cityList.length == 0">
            <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col  :span="7">
        <el-form-item label="反馈日期" >
          <el-date-picker
              @change="console.log(selectForm.dateRange)"
              v-model="selectForm.dateRange"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :offset="1" :span="4">
        <el-form-item >
          <el-button type="danger" @click="clearForm">清空</el-button>
          <el-button @click="initData" type="primary">查询</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-table  v-loading="tableLoading" :data="tableData" style="width: 90%; margin-top: 0.5rem"  stripe v-if="!showPreview">
    <el-table-column fixed sortable min-width="80" label="编号" prop="id"/>
    <el-table-column fixed label="反馈者姓名"  #default="scope">
      <span>{{scope.row.supervisor.realName}}</span>
    </el-table-column>
    <el-table-column label="所在省" #default="scope">
      <span>{{scope.row.confirmAddress.province}}</span>
    </el-table-column>
    <el-table-column label="所在市" #default="scope" >
      <span>{{scope.row.confirmAddress.city}}</span>
    </el-table-column>
    <el-table-column label="预估污染等级" min-width="150"  #default="scope">
      <el-tag v-for="item in aqiToObj(scope.row.aqi)" :color="item.color">
        <span style="color: white">{{item.label}}</span>
      </el-tag>
    </el-table-column>
    <el-table-column label="反馈日期" min-width="100" #default="scope">
      {{scope.row.updateTime.substring(0, 10)}}
    </el-table-column>
    <el-table-column label="反馈时间" #default="scope">
      {{scope.row.updateTime.substring(11, 19)}}
    </el-table-column>
    <el-table-column label="操作" fixed="right"  align="center" min-width="200">
      <template #default="scope">
        <el-button
            icon="document"
            plain
            size="small"
            type="info"
            @click="handlePreview(scope.$index, scope.row)"
        >
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-if="!showPreview"
      class="pageList"
      :page-sizes="[5, 10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
      @size-change="handleSizeChange"
      :current-page="page"
      @current-change="handleCurrentChange">

  </el-pagination>
  <transition name="el-fade-in" mode="out-in">
    <ConfirmAqiPreview
        @cancel-preview="handleClosePreview"
        v-if="showPreview"
        :description="previewData"
        />
  </transition>
</div>
</template>

<style scoped>
@import "../css/main-components.css";
</style>
